{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 桶排序\n",
    "## 将数据分配到n个桶中，对每个桶进行排序再排出来. 元素的分布在 (a, b) 之间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "from Merge_sort import *\n",
    "def Bucket_sort(L,n,a,b):\n",
    "    '''\n",
    "    Input:\n",
    "    - L: the unordered list.\n",
    "    - n: the number of buckets.\n",
    "    - a: the lower bound.\n",
    "    - b: the upper bound.\n",
    "    Output:\n",
    "    - L: the ordered list.\n",
    "    '''\n",
    "    bucket = [[] for i in range(n)]\n",
    "    for i in range(len(L)):\n",
    "        bucket[(L[i] - a) * n // (b - a )].append(L[i])\n",
    "    for i in range(n):\n",
    "        # 对每个 bucket 进行排序\n",
    "        bucket[i] = Merge_sort(bucket[i],0,len(bucket[i])-1)\n",
    "    L = [a for b in bucket for a in b]\n",
    "    return L"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5, 6, 8]\n"
     ]
    }
   ],
   "source": [
    "L = [1,5,6,3,8,4,2]\n",
    "print(Bucket_sort(L,1,0,10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "torch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
